/*
 * @author: liubing
 * @Date: 2020-07-06 20:12:22
 * @desc: 
 */

const vs_source = `
attribute vec4 a_Position;
attribute vec4 a_Color;
varying vec4 v_Color;

void main() {
    gl_Position = a_Position;
    v_Color = a_Color;
}`;

const fs_source = `
precision mediump float;
varying vec4 v_Color;
void main(){
    gl_FragColor = v_Color;
}`;

function main(){
    // console.error('main --> ');

    let canvas = document.getElementById('webgl');
    let gl = canvas.getContext('webgl');

    if(!initShaders(gl,vs_source,fs_source)){
        console.log('init shaders failed');
    }

    let n = initVertexBuffers(gl);
    if(n < 0){
        console.log('Failed to set positions');
        return;
    }

    gl.clearColor(0.0,0.0,0.0,1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLES,0,n);
}

function initVertexBuffers(gl){

    let vertices = new Float32Array([0.0,0.5,-0.5,-0.5,0.5,-0.5]);
    let colors = new Float32Array([
        1.0,0.0,0.0,1.0,
        0.0,1.0,0.0,1.0,
        0.0,0.0,1.0,1.0]);

    // let color = a;
    var n = 3;

    let vertexBuffer = gl.createBuffer(
        [0.0,0.5,-0.5,-0.5,0.5,-0.5]
    );
    if(!vertexBuffer){
        console.log("Failed to create the buffer object ");
        return -1;
    }
    gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW);

    let a_Position = gl.getAttribLocation(gl.program,'a_Position');
    
    gl.vertexAttribPointer(a_Position,2,gl.FLOAT,false,0,0);
    gl.enableVertexAttribArray(a_Position);

   
    let colorBuffer = gl.createBuffer();
    if(!colorBuffer){
        console.log("Failed to create the ColorBuffer");
        return -1
    }
 
    gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);
    gl.bufferData(gl.ARRAY_BUFFER,colors,gl.STATIC_DRAW);

    let a_Color = gl.getAttribLocation(gl.program,'a_Color');
    gl.vertexAttribPointer(a_Color,4,gl.FLOAT,false,0,0);
    gl.enableVertexAttribArray(a_Color);

    // gl.bindBuffer(gl.ARRAY_BUFFER,colorBuffer);

   
    return n;
}